package com.rc.saas.tenant.shiro;

import com.rc.saas.tenant.controller.tenant.IndexController;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Shiro登录机制验证
 * 对指定路径进行拦截,如果/login不带spm参数就拒绝访问,跟SpmInterceptor配合使用
 * 扩展自shiro自带的authc拦截器：org.apache.shiro.web.filter.authc.FormAuthenticationFilter
 * Created by Sven on 2021/02/19
 */
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {
    private static Logger logger = LogManager.getLogger(CustomFormAuthenticationFilter.class);

    /**
     * 当访问拒绝时
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + req.getServletPath();
        logger.info("onAccessDenied:{}", url);

        //获取spm值并保存到会话中(Redis)
        String spm = req.getParameter("spm");
        logger.warn("onAccessDenied,spm:{}", spm);

        if (StringUtils.isNotBlank(spm)) {
            req.getSession().setAttribute("spm", spm);
        }else{
            //req.getSession().removeAttribute("spm");
            //req.getSession().setAttribute("spm", null);
        }
        return true;

        //未登录状态发送的请求都会重定向
//        return super.onAccessDenied(request, response);
    }
}
